package com.example.a1.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.a1.R;
import com.example.a1.activity.BannerDetailActivity;
import com.example.a1.activity.CategoryListActivity;
import com.example.a1.activity.CourseDetailActivity;
import com.example.a1.adapter.BannerAdapter;
import com.example.a1.adapter.CategoryAdapter;
import com.example.a1.adapter.CourseAdapter;
import com.example.a1.model.Banner;
import com.example.a1.model.Category;
import com.example.a1.model.Course;
import com.example.a1.util.HttpUtil;
import com.example.a1.widget.ClickableViewPager;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private ClickableViewPager bannerViewPager;
    private GridView categoryGridView, courseGridView;
    private BannerAdapter bannerAdapter;
    private final List<Banner> bannerList = new ArrayList<>();
    private final List<Category> categoryList = new ArrayList<>();
    private final List<Course> courseList = new ArrayList<>();
    private Handler handler;
    private Runnable bannerRunnable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        initData();
        initListener();
        startBannerLoop();
        return view;
    }

    private void initView(View view) {
        bannerViewPager = view.findViewById(R.id.banner_viewpager);
        categoryGridView = view.findViewById(R.id.category_grid);
        courseGridView = view.findViewById(R.id.course_grid);

        bannerAdapter = new BannerAdapter(requireContext(), bannerList);
        bannerViewPager.setAdapter(bannerAdapter);
        categoryGridView.setAdapter(new CategoryAdapter(requireContext(), categoryList));
        courseGridView.setAdapter(new CourseAdapter(requireContext(), courseList));
    }

    private void initData() {
        // 加载轮播图数据
        HttpUtil.getBannerData(new HttpUtil.OnDataLoadedListener<List<Banner>>() {
            @Override
            public void onSuccess(List<Banner> data) {
                bannerList.clear();
                bannerList.addAll(data);
                bannerAdapter.notifyDataSetChanged();
                if (!bannerList.isEmpty()) {
                    bannerViewPager.setCurrentItem(bannerList.size() * 100);
                }
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(requireContext(), "轮播图加载失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });

        // 加载分类数据
        HttpUtil.getCategoryData(new HttpUtil.OnDataLoadedListener<List<Category>>() {
            @Override
            public void onSuccess(List<Category> data) {
                categoryList.addAll(data);
                ((CategoryAdapter) categoryGridView.getAdapter()).notifyDataSetChanged();
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(requireContext(), "分类加载失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });

        // 加载课程数据
        HttpUtil.getCourseData(new HttpUtil.OnDataLoadedListener<List<Course>>() {
            @Override
            public void onSuccess(List<Course> data) {
                courseList.clear();
                courseList.addAll(data);
                ((CourseAdapter) courseGridView.getAdapter()).notifyDataSetChanged();
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(requireContext(), "课程加载失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initListener() {
        // 轮播图点击事件
        bannerViewPager.setOnItemClickListener(position -> {
            if (bannerList.isEmpty()) return;
            Banner banner = bannerList.get(position % bannerList.size());
            Log.d(TAG, "点击轮播图: " + banner.getTitle() + ", 详情URL: " + banner.getDetailUrl());

            Intent intent = new Intent(requireContext(), BannerDetailActivity.class);
            intent.putExtra("banner_title", banner.getTitle());
            intent.putExtra("banner_detail_url", banner.getDetailUrl());
            startActivity(intent);
        });

        // 分类点击事件（传递分类名称，用于标题显示）
        categoryGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (position < categoryList.size()) {
                Category category = categoryList.get(position);
                Intent intent = new Intent(requireContext(), CategoryListActivity.class);
                intent.putExtra("category_id", category.getId());
                intent.putExtra("category_name", category.getName()); // 传递分类名称
                startActivity(intent);
            }
        });

        // 推荐课程点击事件
        courseGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (position < courseList.size()) {
                Course course = courseList.get(position);
                Intent intent = new Intent(requireContext(), CourseDetailActivity.class);
                intent.putExtra("course_detail_url", course.getDetailUrl());
                startActivity(intent);
            }
        });
    }

    private void startBannerLoop() {
        handler = new Handler(Looper.getMainLooper());
        bannerRunnable = new Runnable() {
            @Override
            public void run() {
                if (bannerViewPager != null && !bannerList.isEmpty()) {
                    int current = bannerViewPager.getCurrentItem();
                    bannerViewPager.setCurrentItem(current + 1);
                    handler.postDelayed(this, 3000);
                }
            }
        };
        handler.postDelayed(bannerRunnable, 3000);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (handler != null) {
            handler.removeCallbacks(bannerRunnable);
        }
    }
}